package com.holdtime.jtt809dataservice.server.socket;

import com.holdtime.jtt809dataservice.common.codec.JTT809Decoder;
import com.holdtime.jtt809dataservice.common.codec.JTT809Encoder;
import com.holdtime.jtt809dataservice.common.filter.MyLoggingFilter;
import com.holdtime.jtt809dataservice.server.handler.SubLinksHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import protocol.jtt809.JTT809Packet;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * author: sunwei
 * Date: 2025/3/14 19:26
 * Description:
 */
@Slf4j
public class TcpClient {
    private EventLoopGroup workerGroup;
    private Bootstrap bootstrap;
    private Channel channel;
    private String host;
    private int port;

    public TcpClient(SubLinksHandler handler, String host, int port, Runnable runnable) {
        this.host = host; // 保存 host
        this.port = port; // 保存 port
        workerGroup = new NioEventLoopGroup();
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        // 设置编码解码器
                        pipeline.addLast(new JTT809Decoder());
                        pipeline.addLast(new JTT809Encoder());
                        // 设置日志过滤器
                        pipeline.addLast(new MyLoggingFilter());
                        // 设置空闲处理器
                        pipeline.addLast(new IdleStateHandler(0, 0, 60, TimeUnit.SECONDS));
                        // 设置处理handler
                        pipeline.addLast(handler);
                    }
                });

        // 设置地址、端口
        bootstrap.remoteAddress(new InetSocketAddress(host, port));

        // 添加监听
        bootstrap.handler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                if (!workerGroup.isShutdown()) {
                    int i = 0;
                    boolean connected = false;
                    while (i < 3 && !connected) {
                        connected = connect();
                        i++;
                        Thread.sleep(2000);
                    }
                    if (!connected) { // 三次重连不成功，主链路发送从链路断开通知消息
                        dispose();
                        if (runnable != null) {
                            runnable.run();
                        }
                    }
                }
            }
        });
    }

    /**
     * 建立连接
     */
    public boolean connect() {
        try {
            ChannelFuture future = bootstrap.connect().sync();
            channel = future.channel();
            return true;
        } catch (Exception e) {
            log.error("从链路连接失败：{}:{}", host, port, e);
        }
        return false;
    }

    /**
     * 关闭连接
     */
    public void close() {
        if (channel != null) {
            channel.close();
            channel = null;
        }
    }

    /**
     * 释放连接
     */
    public void dispose() {
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }

    /**
     * 发送数据
     *
     * @return
     */
    public boolean send(JTT809Packet<?> data) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(data);
            return true;
        }
        return false;
    }

    public boolean send(byte[] data) {
        if (channel != null && channel.isActive()) {
            channel.writeAndFlush(data);
            return true;
        }
        return false;
    }
}
